package net.jcip.chapter2;

import net.jcip.annotations.*;

/**
 * LazyInitRace
 *
 * Race condition in lazy initialization
 *
 * @author Brian Goetz and Tim Peierls
 */

@NotThreadSafe
public class LazyInitRace {
    private ExpensiveObject instance = null;

    private ExpensiveObject getInstance() {
        if (instance == null){
            instance = new ExpensiveObject();
        }
        return instance;
    }

    public static void main(String[] args){


        for (int i = 0; i < 10; i++) {

            new Thread(
                    () -> {
                        ExpensiveObject instance = new LazyInitRace().getInstance();
                        System.out.println(instance.hashCode());
                    }
            ,  "线程 " +i ).start();

        }


    }

}

class ExpensiveObject { }

